package com.example.myblog.component;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author yx
 */
@Component
public class SyncElastic {
    public static final String QUEUE_BLOG_SAVE = "queue.blog.save";
    public static final String QUEUE_BLOG_REMOVE = "queue.blog.remove";
    public static final String BLOG_EXCHANGE = "blog.exchange";
    public static final String KEY_BLOG_SAVE = "key.blog.save";
    public static final String KEY_BLOG_REMOVE = "key.blog.remove";







    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    public void setElasticsearchTemplate(ElasticsearchRestTemplate elasticsearchRestTemplate) {
        this.elasticsearchRestTemplate = elasticsearchRestTemplate;
    }

    /**
     * 将所有数据导入到es
     * @param repository
     * @param list
     * @return
     * @param <T>
     * @param <ID>
     */
    public  <T,ID> Boolean saveAll(ElasticsearchRepository<T,ID> repository, List<T> list) {
        try {
            repository.saveAll(list);
            return Boolean.TRUE;
        } catch (Exception e) {
            return Boolean.FALSE;
        }
    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = QUEUE_BLOG_SAVE,durable = "true"),
                    exchange = @Exchange(value = BLOG_EXCHANGE,type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true")
            ,key = KEY_BLOG_SAVE)
    })
    public void receiveAndSave(String message) {

    }
}
